<%@ Page Language="C#" MasterPageFile="~/Site.master" Title="Nested Repeaters" %>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" Runat="Server">
    <AjaxData:Repeater ID="Repeater1" runat="server" ItemDataBoundEvent="onParentItemDataBound">
        <ItemTemplate>
            <h4 id="h4Category"></h4>
            <ul id="ulProducts"></ul>
        </ItemTemplate>
    </AjaxData:Repeater>

    <script type="text/javascript">

        function pageLoad(sender, e)
        {
            DataService.GetAllCategoryWithProducts(onLoadSuccess);
        }

        function onLoadSuccess(result)
        {
            var repeater = Repeater1;

            repeater.set_dataSource(result);
            repeater.dataBind();
        }

        function onParentItemDataBound(sender, e)
        {
            var item = e.get_item();

            if (item.get_isDataItemType())
            {
                var category = item.get_dataItem();

                var h4Category = item.findControl('h4Category');

                setText(h4Category, category.Name);

                //Here we will load the Product Names in a repeater.
                //First we have to make sure that if the repeater exists we destruy it.
                var ulProducts = item.findControl('ulProducts');
                var childRepeaterID = ulProducts.id;
                var childRepeater = $find(childRepeaterID);

                if (childRepeater)
                {
                    //There is a previous instance so we need to remove it.
                    Sys.Application.removeComponent(childRepeater);
                }

                childRepeater = $create(AjaxDataControls.Repeater, {'itemTemplate': '<li><span id=\"spnProductName\"></span></li>'}, {'itemDataBound': onChildItemDataBound}, null, ulProducts);
                childRepeater.set_dataSource(category.ProductNames);
                childRepeater.dataBind();
            }
        }

        function onChildItemDataBound(sender, e)
        {
            var item = e.get_item();

            if (item.get_isDataItemType())
            {
                var productName = item.get_dataItem();

                var spnName = item.findControl('spnProductName');

                setText(spnName, productName);
            }
        }

        function setText(element, text)
        {
            if (typeof element.textContent != 'undefined')
            {
                element.textContent = text;
            }
            else if (typeof element.innerText != 'undefined')
            {
                element.innerText = text;
            }
        }

    </script>
</asp:Content>